import { Progress, Flex, Table, Button, Col, Row, Image } from "antd";
import { HeartFilled, HeartOutlined } from '@ant-design/icons';
import React, { useRef, useState } from "react";
import { TaskQueue } from "../queue";
import { create_get_chart_task } from "../finviz";

const GetConfig = () => {
    if (window.localStorage.getItem('StockFilters') === 'null') {
        SetConfig({ subscriptionList: [] });
    }
    return JSON.parse(window.localStorage.getItem('StockFilters'));
}

const PushinsubscriptionList = (ticker) => {
    const config = GetConfig();
    config.subscriptionList.push(ticker);
    SetConfig(config);
}

const RemovefromsubscriptionList = (ticker) => {
    const config = GetConfig();
    config.subscriptionList = config.subscriptionList.filter(item => item !== ticker);
    SetConfig(config);
}

const SetConfig = (object) => {
    window.localStorage.setItem('StockFilters', JSON.stringify(object));
}

export const SubscriptionList = React.forwardRef((props, ref) => {
    const componetData = useRef({
        ticketlist: [],
        percent: 0,
    });
    const [ticketlist, setTicketlist] = useState(componetData.current.ticketlist);
    const [percent, setPercent] = useState(componetData.current.percent);

    React.useImperativeHandle(ref, () => ({
        getData: () => componetData.current,
        setData: (data) => componetData.current = data,
    }))

    const TableColumns = [
        {
            title: '订阅',
            dataIndex: 'is_subscription',
            key: 'is_subscription',
            render: (_, record) => {
                return (
                    <Button onClick={() => {
                        RemovefromsubscriptionList(record.ticker);
                        record.is_subscription = !record.is_subscription;
                        componetData.current.ticketlist = componetData.current.ticketlist.filter(item => item.ticker !== record.ticker);
                        setTicketlist(componetData.current.ticketlist);
                    }} icon={record.is_subscription ? <HeartFilled /> : <HeartOutlined />} />
                )
            }
        },
        {
            title: '代码',
            dataIndex: 'ticker',
            key: 'ticker',
        },
        {
            title: '开盘价',
            dataIndex: 'lastOpen',
            key: 'lastOpen',
        },
        {
            title: '最高价',
            dataIndex: 'lastHigh',
            key: 'lastHigh',
        },
        {
            title: '最低价',
            dataIndex: 'lastLow',
            key: 'lastLow',
        },
        {
            title: '收盘价',
            dataIndex: 'lastClose',
            key: 'lastClose',
        },
        {
            title: '成交量',
            dataIndex: 'lastVolume',
            key: 'lastVolume',
        },
        {
            title: '缩略图',
            dataIndex: 'tickerImage',
            key: 'tickerImage',
            render: (imageUrl) => <Image height={80} src={imageUrl} />
        },
    ]

    function Refresh() {
        const subscriptionlist = GetConfig().subscriptionList;

        const tasks = new TaskQueue(20);
        componetData.current.ticketlist = [];
        let count = 0;
        for (const ticker of subscriptionlist) {
            tasks.addTask(create_get_chart_task(ticker, 'd', true, false, 5)).then(data => {
                count++;
                const percent = ((count / subscriptionlist.length) * 100).toFixed(2);

                data.key = count;
                data.is_subscription = true;
                data.lastOpen = data.lastOpen.toFixed(2);
                data.lastHigh = data.lastHigh.toFixed(2);
                data.lastLow = data.lastLow.toFixed(2);
                data.lastClose = data.lastClose.toFixed(2);
                data.lastVolume = (data.lastVolume / 10000).toFixed(2) + 'W';
                data.tickerImage = `https://charts-node.finviz.com/chart.ashx?&t=${data.ticker}&tf=d&s=linear&ct=candle_stick&tm=d`;

                const newTicketlist = [...componetData.current.ticketlist, data];
                componetData.current.ticketlist = newTicketlist;
                setTicketlist(newTicketlist);

                componetData.current.percentRef = Number(percent);
                setPercent(componetData.current.percentRef);
            })

        }

    }

    return (
        <>
            <Flex vertical gap="small">
                <Row>
                    <Col span={2}>
                        <Button onClick={Refresh}>更新列表</Button>
                    </Col>
                    <Col span={22}>
                        <Progress percent={percent} type="line" />
                    </Col>
                </Row>
            </Flex>
            <Table columns={TableColumns} dataSource={ticketlist}></Table>
        </>
    )
})



